package com.qf.ks.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.ks.constans.ResultCode;
import com.qf.ks.exception.AddDataException;
import com.qf.ks.mapper.AuthorsMapper;
import com.qf.ks.mapper.BookMapper;
import com.qf.ks.mapper.CategoriesMapper;
import com.qf.ks.pojo.Authors;
import com.qf.ks.pojo.Books;
import com.qf.ks.pojo.Categories;
import com.qf.ks.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.print.Book;
import java.util.List;

@Service
@Transactional
public class BooksServiceImpl implements BooksService {
    private AuthorsMapper authorsMapper;
    private CategoriesMapper categoriesMapper;
    @Autowired
    public void setAuthorsMapper(AuthorsMapper authorsMapper) {
        this.authorsMapper = authorsMapper;
    }
    @Autowired
    public void setCategoriesMapper(CategoriesMapper categoriesMapper) {
        this.categoriesMapper = categoriesMapper;
    }

    private BookMapper bookMapper;
    @Autowired
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @Override
    public void AddBooks(Books books) {
        if (books.getBookname()==null){
            throw new AddDataException("书名为空", ResultCode.NULL_BOOKNAME);
        }
        if (books.getAuthorid()==0){
            throw new AddDataException("作者为空", ResultCode.NULL_AUTHORS);
        }
        if (books.getCategoryid()==0){
            throw new AddDataException("图书类型为空", ResultCode.NULL_CATEGORIES);
        }
        bookMapper.AddBooks(books);
    }

    @Override
    public PageInfo<Books> getAllBookByBookNameOrByAuthorName(String name, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Books> booksList = bookMapper.findAllBooks(name);
        if (booksList==null){
            throw new AddDataException("暂时没有上架", ResultCode.NULL_BOOKS);
        }
        for (Books books:booksList) {
            Authors authors = authorsMapper.selectAuthorsById(books.getAuthorid());
            Categories categories = categoriesMapper.CategoriesById(books.getCategoryid());
            books.setAuthors(authors);
            books.setCategories(categories);
        }
        PageInfo<Books> books =new PageInfo<>(booksList);
        return books;
    }
}
